import axios from 'axios'
import store from '@/store'
import { message } from 'antd'
import { logout } from '@/store/actions'
import { history } from '@/utils/history'

export const http = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0',
  timeout: 5000,
})

http.interceptors.request.use((config) => {
  //统一添加token
  if (!config.url.startsWith('/authorizations')) {
    config.headers.Authorization = 'Bearer ' + store.getState().login
  }
  return config
})

http.interceptors.response.use(undefined, (error) => {
  //如果响应超时，没有response属性
  if (!error?.response) {
    return message.warn('网络超时')
  }
  if (error.response.status === 401) {
    //如果token失效，重新跳转到登录页面
    message.error('登录超时，请重新登录', 1.5, () => {
      store.dispatch(logout())
      //重定向到登录页面
      history.push('/login')
    })
  }
  return Promise.reject(error)
})
